import React, { useState, useMemo } from "react";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { ChevronRight, ChevronDown } from "lucide-react";

// 辅助函数：将扁平的标题列表转换为树形结构
const buildTree = (headings) => {
  const tree = [];
  const path = [];
  
  headings.forEach(heading => {
    while (path.length > 0 && path[path.length - 1].level >= heading.level) {
      path.pop();
    }
    
    const node = { ...heading, children: [] };
    
    if (path.length === 0) {
      tree.push(node);
    } else {
      path[path.length - 1].children.push(node);
    }
    
    path.push(node);
  });
  
  return tree;
};

// 递归渲染目录项
const TocNode = ({ node, onSectionClick }) => {
  const [isOpen, setIsOpen] = useState(true);
  const hasChildren = node.children && node.children.length > 0;

  return (
    <Collapsible open={isOpen} onOpenChange={setIsOpen} className="pl-4">
      <div className="flex items-center gap-1 group">
        {hasChildren ? (
          <CollapsibleTrigger asChild>
            <button className="p-1 -ml-6">
              {isOpen ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
            </button>
          </CollapsibleTrigger>
        ) : (
          <div className="w-3 h-3 -ml-5 mr-1" />
        )}
        <span 
          className="cursor-pointer text-sm text-gray-700 hover:text-blue-600 truncate flex-1"
          onClick={() => onSectionClick(node.id)}
          title={node.title}
        >
          {node.title}
        </span>
      </div>
      {hasChildren && (
        <CollapsibleContent>
          <div className="pt-1 border-l border-gray-200 ml-[7px]">
            {node.children.map((child, index) => (
              <TocNode key={index} node={child} onSectionClick={onSectionClick} />
            ))}
          </div>
        </CollapsibleContent>
      )}
    </Collapsible>
  );
};

export default function CollapsibleToc({ content, onSectionClick }) {
  const headings = useMemo(() => {
    const headingList = [];
    if (!content) return headingList;
    
    // 使用更健壮的正则表达式来匹配标题，并为它们创建ID
    const headingRegex = /^(#{1,6})\s+(.*)/gm;
    let match;
    let index = 0;
    while ((match = headingRegex.exec(content)) !== null) {
      const level = match[1].length;
      const title = match[2].trim();
      const id = `heading-${index++}-${title.toLowerCase().replace(/\s+/g, '-')}`;
      headingList.push({ id, title, level });
    }
    return headingList;
  }, [content]);

  const tree = useMemo(() => buildTree(headings), [headings]);

  if (tree.length === 0) {
    return <p className="text-gray-500 text-sm p-4">暂无标题章节</p>;
  }

  return (
    <div className="space-y-1 py-2">
      {tree.map((node, index) => (
        <TocNode key={index} node={node} onSectionClick={onSectionClick} />
      ))}
    </div>
  );
}